<template>
  <div class="app-login">
    <el-card class="app-login__content" shadow="hover">
      <template #header>
        <h4>玲玲商城管理系统</h4>
      </template>
      <el-form
        ref="formInstance"
        :model="values"
        :rules="rules"
        label-width="60px"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="values.username" />
        </el-form-item>
        <el-form-item label="密  码" prop="password">
          <el-input type="password" show-password v-model="values.password" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">登录</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>
<script>
  import { mapActions } from 'vuex'
  export default {
    name: 'AppLogin',
    data () {
      return {
        values: {
          username: '',
          password: ''
        },
        rules: {
          username: [
            { required: true, message: '快点输入用户名', trigger: 'blur' },
          ],
          password: [
            // 注意, methods的执行顺序比data快
            { validator: this.handleValidatePassword , trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      ...mapActions('authority', ['loginPostAction']),
      handleValidatePassword (rule, value, callback) {
        if (!value) return callback(new Error('密码不能为空'))
        if (this.values.username && this.values.username === value) {
          return callback(new Error('用户名和密码不能一样'))
        }
        callback()
      },
      handleReset () {
        this.$refs.formInstance.resetFields()
      },
      async handleSubmit () {
        this.$refs.formInstance.validate(async (valid, fields) => {
          if (valid) {
            const result = await this.loginPostAction(this.values)
            // 登录成功后, 跳转页面
            result && this.$router.replace({ name: 'home' })
          } else {
            this.$message({ message: '表单验证失败', type: 'error' })
          }
        })
      }
    }
  }
</script>
<style lang="scss" scoped>
  .app-login {
    height: 100%;
    position: relative;
    &__content{
      width: 400px;
      height: 220px;
      position: absolute;
      left: 0; right: 0; bottom: 0; top: 0;
      margin: auto;
    }
  }
</style>
